package com.tmt.im.service.helper;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.tmt.im.common.Constant;
import com.tmt.im.service.controller.vo.OperationFailInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/9/17 22:16
 * @Version 1.0
 **/
public class OperationFailInfoHelper {

    public static List<OperationFailInfo> convertTo(JSONObject jsonObject) {
        Long code = jsonObject.getLong("code");
        if (code != 200L){
            return new ArrayList<>();
        }

        if ("V9".equalsIgnoreCase(Constant.YUN_XIN_API_VERSION)) {
            return convertTo_V9(jsonObject);
        }
        return convertTo_V10(jsonObject);
    }

    private static List<OperationFailInfo> convertTo_V9(JSONObject jsonObject) {
        List<OperationFailInfo> list = new ArrayList<>();
        if (jsonObject.containsKey("faccid")) {
            JSONObject json = jsonObject.getJSONObject("faccid");
            String errMsg = json.getString("msg");
            String[] errorMsgArray = errMsg.split("\\|");
            JSONArray ids = json.getJSONArray("accid");
            for (int i = 0; i < ids.size(); i++) {
                Long memberId = Long.parseLong(ids.get(i).toString());
                String err = errorMsgArray[Math.min(i, errorMsgArray.length -1)];
                int code = -1;
                if (err.contains("=")) {
                    try {
                        code = Integer.parseInt(err.split("=")[0]);
                        err = err.split("=")[1];
                    }catch (Exception ex){}
                }
                OperationFailInfo info = new OperationFailInfo(memberId, code, err);
                list.add(info);
            }
        }
        return list;
    }

    private static List<OperationFailInfo> convertTo_V10(JSONObject jsonObject) {
        List<OperationFailInfo> list = new ArrayList<>();
        JSONObject json = jsonObject.getJSONObject("data");
        if (json.containsKey("failed_list")) {
            JSONArray items = json.getJSONArray("failed_list");
            for (Object obj : items) {
                JSONObject jsonObj = JSONObject.from(obj);
                Long memberId = Long.parseLong(jsonObj.getString("account_id"));
                Long errorCode = jsonObj.getLong("error_code");
                String errorMsg = jsonObj.getString("error_msg");
                OperationFailInfo info = new OperationFailInfo(memberId, errorCode.intValue(), errorMsg);
                list.add(info);
            }
        }
        return list;
    }
}
